package com.xiaocg.sparse.linkedlist;

/**
 * @author xiaocg
 * 单链表
 */
public class SingleLinkedList {

    /**
     *  定义头结点,不存放具体数据
     */
    private CustomNode head = new CustomNode();

    public CustomNode getHead() {
        return head;
    }

    public boolean isEmpty(){
        return this.head.getNext() == null;
    }

    /**
     * 找到最后一个节点 尾插法
     * @param node
     */
    public void add(CustomNode node){
        CustomNode temp = head;
        while (temp.getNext() != null) {
            temp = temp.getNext();
        }
        temp.setNext(node);

    }

    /**
     * 先找到需要删除节点的前一个节点
     * @param node
     */
    public void deleteNode(CustomNode node){

        if (head.getNext() == null){
            System.out.println("链表为空");
            return;
        }

        CustomNode temp = head;
        boolean flag = false;
        while (temp.getNext() != null) {
            if (temp.getNext().getNo() == node.getNo()) {
                flag = true;
                break;
            }
            temp = temp.getNext();
        }

        if (flag){
            temp.setNext(temp.getNext().getNext());
        }else{
            System.out.println("删除的节点不存在");
        }



    }

    /**
     * 根据序号修改节点的name
     * @param node
     */
    public void update(CustomNode node){
        if (head.getNext() == null){
            System.out.println("链表为空");
            return;
        }
        CustomNode temp = head.getNext();
        boolean flag = false;
        while (temp != null) {
            if (temp.getNo() == node.getNo()) {
                flag = true;
                break;
            }
            temp = temp.getNext();
        }
        if (flag) {
            temp.setName(node.getName());
        }else {
            System.out.println("需要修改的节点不存在");
        }

    }

    /**
     * 根据节点序号有序添加
     * @param node
     */
    public void addByNo(CustomNode node){
        CustomNode temp = head;

        boolean flag = false;
        while (true){
            if (temp.getNext() == null){
                break;
            }
            if (temp.getNext().getNo()>node.getNo()){
                break;
            }else if(temp.getNext().getNo() == node.getNo()){
                //此时已经添加过了
                flag = true;
                break;
            }
            temp = temp.getNext();
        }

        if (flag){
            System.out.println(node.toString()+":已经存在");
            return;
        }
        //先把找到的temp的节点下一个节点挂到需要添加的node节点下
        node.setNext(temp.getNext());
        //再把node节点添加到temp节点的next
        temp.setNext(node);

    }

    /**
     * 打印节点
     */
    public void list(){
        if (head.getNext()==null){
            System.out.println("链表为空");
            return;
        }
        CustomNode temp = head.getNext();
        while (temp!=null){
            System.out.println("node:"+temp.toString());
            temp = temp.getNext();
        }

    }

}
